package controllers

import (
	"encoding/json"
	"strconv"
	"strings"
	"time"

	"monitor/models"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/cache"
)

type Rate struct {
	Num     string
	Rate    string
	MaxRate string
	MinRate string
}

type Stat struct {
	Name    string
	Host    string
	Expired bool
	Values  []*Rate
}

type StatsController struct {
	beego.Controller
}

func (this *StatsController) Get() {

	app := this.GetString("app")

	statArray := make([]*Stat, 0)

	ks := models.Keys[app]
	if ks != nil {
		keys, err := models.Rc.Do("KEYS", app+"*")

		if err == nil {
			for _, key := range keys.([]interface{}) {
				stat := &Stat{}
				arr := strings.Split(cache.GetString(key), "|")
				if arr != nil && len(arr) > 1 {
					host := arr[1]
					name := arr[2]
					stat.Host = host
					stat.Name = name
					value := map[string]string{}
					json.Unmarshal([]byte(cache.GetString(models.Rc.LGet(cache.GetString(key)))), &value)
					if len(ks) > 0 {
						rates := make([]*Rate, 0)
						for _, k := range ks {
							rate := &Rate{}
							rate.Num = value[k]
							rate.Rate = value[k+"Rate"]
							ratesKey := time.Now().Format("2006-01-02") + "|" + app + "|" + host + "|" + name
							rate.MaxRate = strconv.Itoa((models.Rates[ratesKey])[k+"Max"])
							rate.MinRate = strconv.Itoa((models.Rates[ratesKey])[k+"Min"])
							rates = append(rates, rate)
						}
						stat.Values = rates
					}

					t, _ := strconv.Atoi(value["t"])
					now := time.Now().Unix()
					if now-int64(t) >= 60 {
						stat.Expired = true
					}
					statArray = append(statArray, stat)
				}
			}
		}
		this.Data["keys"] = ks
	}

	BubbleSort(statArray)
	this.Data["data"] = statArray

	kestrels := models.Rc.LGetAll("kestrel." + app)
	if kestrels != nil {
		kestrelStats := models.KestrelStats(kestrels)
		this.Data["kestrelStats"] = kestrelStats
	}

	this.Data["app"] = app
	this.TplNames = "stats.tpl"
}

func BubbleSort(values []*Stat) {
	flag := true
	for i := 0; i < len(values)-1; i++ {
		flag = true
		for j := 0; j < len(values)-i-1; j++ {
			if values[j].Host+values[j].Name > values[j+1].Host+values[j+1].Name {
				values[j], values[j+1] = values[j+1], values[j]
				flag = false
			}
		}
		if flag == true {
			break
		}
	}
}
